package com.example.stmp.Service.Department;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.stmp.Entity.Department;
import com.example.stmp.Mapper.DepartmentMapper;
import com.example.stmp.pojo.PageResult;
import com.example.stmp.pojo.Tool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    /*
     * 新增部门
     * */
    @Override
    public void save(Department department) {

        //向部门表中插入一条数据
        department.setCreateTime(Tool.ceareNowTime());
        department.setLastUpdateTime(Tool.ceareNowTime());
        department.setDepartId((departmentMapper.count() + 1) + "");
        departmentMapper.insert(department);

    }

    /*
     * 根据id查询部门
     * */
    @Override
    public Department getById(Long id) {

        Department department = departmentMapper.selectDepartInfoById(id);
        return department;

    }

    /*
     * 查询部门信息
     * */
    @Override
    public List<Department> list() {

        List<Department> departmentList = departmentMapper.selectDepartInfo();

        return departmentList;
    }

    /*
     * 修改部门信息
     * */
    @Override
    @Transactional
    public void update(Department department) {

        //1.查询部门信息
        Department departmentInfo = departmentMapper.selectDepartInfoById(Long.parseLong(department.getDepartId()));

        //2.设置更新时间
        department.setLastUpdateTime(Tool.ceareNowTime());

        //3.修改部门信息
        departmentMapper.update(department);


    }

    /*
     * 部门分页查询
     * */
    @Override
    public PageResult pageQuery(Integer pageNum, Integer pageSize) {

        Long total = departmentMapper.selectcount();
        int startIndex = (pageNum - 1) * pageSize;
        List<Department> departmentList = departmentMapper.pageQuery(startIndex, pageSize);
        return new PageResult(total, departmentList);
    }


    /*
     * 删除部门
     * */
    @Override
    public void delete(List<Long> ids) {

        Department department = null;
        for (Long id : ids) {
            //获取当前状态
            int status = departmentMapper.selectDepartStatusById(id);
            if(status == 1) {
                departmentMapper.updateDepartStatus(id, 0);
            } else {
                departmentMapper.updateDepartStatus(id, 1);
            }
            //更新修改时间
            department = departmentMapper.selectDepartInfoById(id);
            department.setLastUpdateTime(Tool.ceareNowTime());
            departmentMapper.update(department);
        }

    }
}
